﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Lamex.Library;
using DevExpress.Utils;
using DevExpress.XtraGrid.Views.Card;
using DevExpress.XtraGrid.Views.Card.ViewInfo;
using DevExpress.XtraGrid.Views.Layout;
using System.Collections;

namespace Lamex.mMES.UI
{
    public partial class frmMES_Operation_Workshop_Overview : frmBaseChild
    {
        string strSql1, strSql2, strSql3;
        DataTable dt;

        public frmMES_Operation_Workshop_Overview()
        {
            InitializeComponent();
        }

        private void frmMES_Operation_Workshop_Overview_Load(object sender, EventArgs e)
        {
            //当出现布局更改后无法刷新到新样式，将layoutViewCard1.CustomizationFormText改为任意字符串
            //重生成后，可改为默认的TemplateCard
            //layoutViewCard1.CustomizationFormText = "TemplateCard";

            initialLayoutViewProperies(layoutView1,"分厂实时数据");
            initialLayoutViewProperies(layoutView2, "站点实时数据");
            initialLayoutViewProperies(layoutView3, "工序实时数据");

            //节假日可能无数据（未生产）
            dateEditSelectedDate.DateTime = System.DateTime.Now;

            getGridViewSQL();

            doSqlQuery(gridControl1, layoutView1, strSql1);
            doSqlQuery(gridControl2, layoutView2, strSql2);
        }

        //初始化设置LayoutView
        private void initialLayoutViewProperies(LayoutView layoutView,string strCap)
        {
            layoutView.OptionsView.ShowViewCaption = true;//显示视图标题
            layoutView.ViewCaption = strCap;//设置视图标题
            layoutView.Appearance.ViewCaption.TextOptions.HAlignment = HorzAlignment.Near;//标题左对齐

            //layoutView.OptionsView.ShowHeaderPanel = false;//隐藏顶部工具栏

            //设置显示方式，先横后竖，最大显示列数，垂直方向翻页（这几个属性配合使用）
            layoutView.OptionsView.ViewMode = LayoutViewMode.MultiRow;
            //layoutView.OptionsMultiRecordMode.MaxCardColumns = 2;
            layoutView.OptionsMultiRecordMode.MultiRowScrollBarOrientation = ScrollBarOrientation.Vertical;

            //layoutView.OptionsView.ShowCardCaption = false;//隐藏卡片标题，不隐藏，避免漏项
            layoutView.OptionsMultiRecordMode.MaxCardColumns = -1;//不起作用，卡片改为横向顺序排列

            //隐藏字段名
            //Run Designer-Layout-Template Card-(选择操作列，右键选Hidde Text 或设置 TextVisible=False)

            //用于配件看板必须设成分割式，提醒用户避免漏项
            //因排版问题（无法达到想要的效果），改为加不隐藏卡片标题
            //layoutView.OptionsView.CardArrangeRule = LayoutCardArrangeRule.AllowPartialCards;

            layoutView.OptionsBehavior.Editable = false;//禁止编辑
            layoutView.OptionsCustomization.AllowSort = false;//禁止排序
            layoutView.OptionsCustomization.AllowFilter = false;//禁止筛选
        }

        private void getGridViewSQL()
        {
            string curDate = dateEditSelectedDate.Text.ToString();

            //分厂已检查，工作站与工作中心待与frmEFF_Efficiency_Analyse验证结果一致，如有修改，须重新验证！！！
            #region 查询SQL
            strSql1 = @"SELECT c.SUB_FACTORY AS 分厂,CAST(c.Part_QTY AS DECIMAL(18,1)) AS 入仓,CAST(c.PROCESS_TIME AS DECIMAL(18,1)) AS 工时,
                    CAST(d.WORKING_HOURS AS DECIMAL(18,1)) AS 人工,CAST(c.PROCESS_TIME/d.WORKING_HOURS AS DECIMAL(18,3)) AS 效率,状态
                    FROM
                    (SELECT DISTINCT a.SUB_FACTORY,b.Part_QTY,b.PROCESS_TIME,CASE WHEN b.Part_QTY>0 THEN '生产中' ELSE '未生产' END AS 状态
                    FROM View_OP_Resource_Plan AS a
                    LEFT JOIN
                    (SELECT SUB_FACTORY,SUM(InsideQty*Part_QTY/Order_QTY) AS Part_QTY,
                    SUM(InsideQty*Part_QTY/Order_QTY*COMB_TIME)/3600 AS PROCESS_TIME
                    FROM View_OP_Inside_Detail
                    WHERE Scn_Date='" + curDate + @"' 
                    GROUP BY SUB_FACTORY) AS b
                    ON a.SUB_FACTORY=b.SUB_FACTORY) AS c
                    LEFT JOIN
                    (SELECT SUB_FACTORY,WORKING_HOURS
                    FROM HR_Work_Hours_By_SubFactory_Cancel
                    WHERE WORKING_DATE='" + curDate + @"') AS d
                    ON c.SUB_FACTORY=d.SUB_FACTORY 
                    ORDER BY c.SUB_FACTORY DESC";

            strSql2 = @"SELECT c.WORKSTATION AS 站点,CAST(c.Part_QTY AS DECIMAL(18,1)) AS 入仓,CAST(c.PROCESS_TIME AS DECIMAL(18,1)) AS 工时,
                    CAST(d.WORKING_HOURS AS DECIMAL(18,1)) AS 人工,CAST(c.PROCESS_TIME/d.WORKING_HOURS AS DECIMAL(18,3)) AS 效率,状态
                    FROM
                    (SELECT DISTINCT a.WORKSTATION,b.Part_QTY,b.PROCESS_TIME,CASE WHEN b.Part_QTY>0 THEN '生产中' ELSE '未生产' END AS 状态
                    FROM View_OP_Resource_Plan AS a
                    LEFT JOIN
                    (SELECT WORKSTATION,SUM(InsideQty*Part_QTY/Order_QTY) AS Part_QTY,
                    SUM(InsideQty*Part_QTY/Order_QTY*COMB_TIME)/3600 AS PROCESS_TIME
                    FROM View_OP_Inside_Detail
                    WHERE Scn_Date='" + curDate + @"' 
                    GROUP BY WORKSTATION) AS b
                    ON a.WORKSTATION=b.WORKSTATION) AS c
                    LEFT JOIN
                    (SELECT WORKSTATION,WORKING_HOURS
                    FROM HR_Work_Hours_By_Workstation_Cancel
                    WHERE WORKING_DATE='" + curDate + @"') AS d
                    ON c.WORKSTATION=d.WORKSTATION";

            strSql3 = @"SELECT c.PROCESS_CODE AS 代码,c.PROCESS_CODE+'_'+c.PROCESS_NAME AS 工序,CAST(c.Part_QTY AS DECIMAL(18,1)) AS 入仓,CAST(c.PROCESS_TIME AS DECIMAL(18,1)) AS 工时,
                    CAST(d.WORKING_HOURS AS DECIMAL(18,1)) AS 人工,CAST(c.PROCESS_TIME/d.WORKING_HOURS AS DECIMAL(18,3)) AS 效率,状态
                    FROM
                    (SELECT a.PROCESS_CODE,a.PROCESS_NAME,b.Part_QTY,b.PROCESS_TIME,CASE WHEN b.Part_QTY>0 THEN '生产中' ELSE '未生产' END AS 状态
                    FROM View_OP_Resource_Plan AS a
                    LEFT JOIN
                    (SELECT PROCESS_CODE,SUM(InsideQty*Part_QTY/Order_QTY) AS Part_QTY,
                    SUM(InsideQty*Part_QTY/Order_QTY*COMB_TIME)/3600 AS PROCESS_TIME
                    FROM View_OP_Inside_Detail
                    WHERE Scn_Date='" + curDate + @"' 
                    GROUP BY PROCESS_CODE) AS b
                    ON a.PROCESS_CODE=b.PROCESS_CODE) AS c
                    LEFT JOIN
                    (SELECT WORK_CENTER,WORKING_HOURS
                    FROM HR_Work_Hours_By_WorkCenter_Cancel
                    WHERE WORKING_DATE='" + curDate + @"') AS d
                    ON c.PROCESS_CODE=d.WORK_CENTER";

            #endregion
        }

        private void doSqlQuery(DevExpress.XtraGrid.GridControl gc, LayoutView lv,string strSql)
        {
            //lv.Columns.Clear();

            //因多次调用，会刷新多次，不再提示
            //using (WaitDialogForm wdf = new WaitDialogForm("请稍侯", "数据分析中......", new Size(400, 80)))
            //{
                dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(strSql);
                //gc.DataSource = null;
                gc.DataSource = dt;
            //}
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton1.Checked == true)
            {
                searchControl1.Enabled = false;

                gridControl2.Visible = true;
                gridControl2.Dock = DockStyle.Fill;
                gridControl3.Visible = false;
                gridControl3.Dock = DockStyle.None;

                getGridViewSQL();
                doSqlQuery(gridControl1, layoutView1, strSql1);
                doSqlQuery(gridControl2, layoutView2, strSql2);
            }
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton2.Checked == true)
            {
                searchControl1.Enabled = true;

                gridControl2.Visible = false;
                gridControl2.Dock = DockStyle.None;
                gridControl3.Visible = true;
                gridControl3.Dock = DockStyle.Fill;

                getGridViewSQL();
                doSqlQuery(gridControl1, layoutView1, strSql1);
                doSqlQuery(gridControl3, layoutView3, strSql3);
            }           
        }

        //private void layoutView1_CustomDrawCardCaption(object sender, DevExpress.XtraGrid.Views.Layout.Events.LayoutViewCustomDrawCardCaptionEventArgs e)
        //{
        //    //未高度成功，改为直接在LAYOUT显示主字段作标题
        //    LayoutView view = sender as LayoutView;
        //    //    (e.CardInfo as CardInfo).CaptionInfo.CardCaption = view.GetRowCellDisplayText(e.RowHandle, view.Columns[0]);
        //}

        ////更改gridcontrol控件cardview的cardCaption标题
        //private void cardView1_CustomDrawCardCaption(object sender, DevExpress.XtraGrid.Views.Card.CardCaptionCustomDrawEventArgs e)
        //{
        //    CardView view = sender as DevExpress.XtraGrid.Views.Card.CardView;
        //    (e.CardInfo as CardInfo).CaptionInfo.CardCaption = view.GetRowCellDisplayText(e.RowHandle, view.Columns[0]);
        //}

        //private void cardView2_CustomDrawCardCaption(object sender, DevExpress.XtraGrid.Views.Card.CardCaptionCustomDrawEventArgs e)
        //{
        //    CardView view = sender as DevExpress.XtraGrid.Views.Card.CardView;
        //    (e.CardInfo as CardInfo).CaptionInfo.CardCaption = view.GetRowCellDisplayText(e.RowHandle, view.Columns[0]);
        //}

        private void dateEditSelectedDate_TextChanged(object sender, EventArgs e)
        {
            getGridViewSQL();

            if (radioButton1.Checked == true)
            {
                doSqlQuery(gridControl1, layoutView1, strSql1);
                doSqlQuery(gridControl2, layoutView2, strSql2);
            }
            else if (radioButton2.Checked == true)
            {
                doSqlQuery(gridControl1, layoutView1, strSql1);
                doSqlQuery(gridControl3, layoutView3, strSql3);
            }
        }

        //如何在DevExpress GridControl的一列中显示外部图片？
        //https://www.devexpresscn.com/DevExpress-Resources/Demo-13.html
        //以上参考少了下面两句
        string ImageDir = @"L:\MES\Resources\Location\";
        Hashtable Images = new Hashtable();

        //获取文件路径
        string GetFileName(string Location)
        {
            if (Location == null || Location == string.Empty)
                return string.Empty;
            return Location + ".png";
        }

        string strFilePath, strName, strFileName;
        Image img;
        Bitmap pbitmap;

        private void layoutView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.Column.FieldName == "LocationImage" && e.IsGetData)
            {
                LayoutView view = sender as LayoutView;
                strName = (string)((DataRowView)e.Row)["分厂"];
                strFileName = GetFileName(strName);//.ToLower();
                getImageFile();
                e.Value = Images[strFileName];
            }

            if (e.Column.FieldName == "StadusImage" && e.IsGetData)
            {
                LayoutView view = sender as LayoutView;
                strName = (string)((DataRowView)e.Row)["状态"];
                strFileName = GetFileName(strName);//.ToLower();
                getImageFile();
                e.Value = Images[strFileName];
            } 
        }

        private void layoutView2_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.Column.FieldName == "LocationImage" && e.IsGetData)
            {
                LayoutView view = sender as LayoutView;
                strName = (string)((DataRowView)e.Row)["站点"];
                strFileName = GetFileName(strName);//.ToLower();
                getImageFile();
                e.Value = Images[strFileName];
            }

            if (e.Column.FieldName == "StadusImage" && e.IsGetData)
            {
                LayoutView view = sender as LayoutView;
                strName = (string)((DataRowView)e.Row)["状态"];
                strFileName = GetFileName(strName);//.ToLower();
                getImageFile();
                e.Value = Images[strFileName];
            } 
        }

        private void layoutView3_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.Column.FieldName == "LocationImage" && e.IsGetData)
            {
                LayoutView view = sender as LayoutView;
                strName = (string)((DataRowView)e.Row)["代码"];
                strFileName = GetFileName(strName);//.ToLower();
                getImageFile();
                e.Value = Images[strFileName];
            }

            if (e.Column.FieldName == "StadusImage" && e.IsGetData)
            {
                LayoutView view = sender as LayoutView;
                strName = (string)((DataRowView)e.Row)["状态"];
                strFileName = GetFileName(strName);//.ToLower();
                getImageFile();
                e.Value = Images[strFileName];
            }
        }

        private void getImageFile()
        {
            if (!Images.ContainsKey(strFileName))
            {
                img = null;
                pbitmap = null;
                try
                {
                    //string filePath = DevExpress.Utils.FilesHelper.FindingFileName(Application.StartupPath, ImageDir + fileName, false);
                    strFilePath = DevExpress.Utils.FilesHelper.FindingFileName(ImageDir, strFileName, false);
                    //原色加载
                    //img = Image.FromFile(filePath);

                    //去白底加载
                    Image temp = Image.FromFile(strFilePath);
                    pbitmap = new Bitmap(temp);
                    pbitmap.MakeTransparent(Color.White);
                }
                catch
                {
                }
                //Images.Add(fileName, img);
                Images.Add(strFileName, pbitmap);
            }
        }

        private void 入仓ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 效率ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 员工数ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

    }
}